#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Blueprint, url_for, jsonify, redirect, flash, render_template, request
from blog import login_manager
from flask_login import login_required, login_user, logout_user
from blog.models import *
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, validators

admin = Blueprint('admin', __name__, url_prefix='/admin')


# 定义登录form
class RegistrationForm(FlaskForm):
    username = StringField('Username:', [
        validators.Length(min=4, max=25),
        validators.DataRequired(message='Username must!!'),
    ])  # label名称；验证规则
    password = PasswordField('Email:', [
        validators.DataRequired(message='Email must!!'),
        validators.Length(min=2, max=100)
    ])
    submit = SubmitField()


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(user_id)


@admin.route('/index')
@login_required  # 通过装饰器判断是否登录，否则跳转登录页
def index():
    return render_template('index.html')


@admin.route('/login', methods=('GET', 'POST'))
def login():
    form = RegistrationForm()
    # is_submitted可以验证wtform数据，并判断是否为post请求
    if form.is_submitted():
        if form.validate_on_submit():
            # 查询用户名和密码
            username = request.form.get('username')
            password = request.form.get('password')

            user = User.query.filter(User.username == username, User.password == password).first()
            if user:
                # 获取成功登录的用户实例
                # 执行flask-login存储用户到session
                if login_user(user):
                    next = request.args.get('next')  # 获取页面来源url
                    if next is not None:
                        return redirect(next)

                    return redirect(url_for('admin.index'))  # url_for中地址 为蓝图的name参数名称
            else:
                return '账号信息错误'
        else:
            print(url_for('admin.index'))
            return jsonify(form.errors)  # 返回json串
    else:
        return render_template('login.html', form=form)


@admin.route('/logout')
def logout():
    logout_user()
    return redirect('index')
